const chromeMng = require('../mng/chromeMng.20180824'),
    log = require('../util/log')

exports.start = async () => {
    if (!chromeMng.client) {
        log('chrome未连接')
        return
    }
    if (chromeMng.busy) {
        log('chrome繁忙')
        return
    }
    log('占用chrome')
    chromeMng.busy = true
    var result = await chromeMng.checkLoginTaobao()
    if (!result) {
        log('未登录淘宝联盟，释放chrome')
        chromeMng.busy = false
        return
    }
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = chromeMng.client;
    log('抓取https://pub.alimama.com/myunion.htm#!/report/detail/taoke?pageNo=1&payId=&timeId=1')
    await Page.navigate({
        url: 'https://pub.alimama.com/myunion.htm#!/report/detail/taoke?pageNo=1&payId=&timeId=1'
    })
    step2()
}

async function step2(url) {
    if (!chromeMng.busy) {
        return new Promise(resolve => {
            resolve()
        })
    }
    const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = chromeMng.client;
    var {result} = await Runtime.evaluate({expression: 'location.href'})
    if (result.value == url) {
        return new Promise(resolve => {
            log('获取淘宝订单超时，释放chrome')
            chromeMng.busy = false
            resolve()
        })
    }
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            step2(result.value).then(result => {
                resolve(result)
            }, result => {
                reject(reject)
            })
        }, 5000)
    })
}
